﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WatiN.Core;
using System.Diagnostics;
using System.Xml;

namespace AutoCokeZeroTest
{
    public class Program
    {
        Dictionary<string, string> result = new Dictionary<string, string>();
        
        [STAThread]
        static void Main(string[] args)
        {
            //Xml2Html.Transform("Xml2Html.xslt", "FinalResult.xml", "html.html");
            Program myTest = new Program();
            myTest.CheckEmeaMarketUrls();
            myTest.CheckBlogPage();
            myTest.ResultToXml();
            SendMail sm = new SendMail();
            sm.MailProperties(Xml2Html.Transform("Xml2Html.xslt", "FinalResult.xml"));
            bool isSend = sm.Send();
        }
        //Main method for check the Emea Market url
        public void CheckEmeaMarketUrls()
        {
            
            List<string> EmeaMarketUrls = new List<string>();
            //Load Emea Market Urls from UrlList.xml file
            int LoadNum = LoadUrlFromFile(EmeaMarketUrls, "root/EmeaMarketUrls/url");
            if (LoadNum != 0)
            {
                Console.WriteLine("Emea Market load " + LoadNum + " urls");
            }
            else
            {
                Console.WriteLine("Load Emea Market urls failed");
            }
            //Do check for each url for Emea Market
            foreach (string url in EmeaMarketUrls)
            {   
                BrowserDriver br = new BrowserDriver();
                try
                {
                    br.Invoke(BrowserType.InternetExplorer);
                    br.NavigateTo(url);
                    if (br.PageTitle.ToLower().Contains("page not found") || br.PageTitle.Contains("404"))
                    {
                        Console.WriteLine(br.PageTitle + " --- Checked Failed");
                        result.Add(br.PageTitle + "(" + br.URL + ")" +" --- Layout Checked Failed (TestCase#1215773)", "Failed");
                    }
                    else
                    {
                        Console.WriteLine(br.PageTitle + " --- Checked Pass");
                        result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Layout Checked Pass (TestCase#1215773)", "Pass");
                    }
                    CloseAllIEWindows();
                }
                catch (Exception e)
                {
                    Console.WriteLine(br.PageTitle + " Checked Failed");
                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Layout Checked Failed (TestCase#1215773)", "Failed");
                }
            }
        }

        //Main method for check the Blog Page url
        public void CheckBlogPage()
        {        
            //Load Blog urls from UrlList.xml file
            List<string> BlogPageUrls = new List<string>();
            int LoadNum = LoadUrlFromFile(BlogPageUrls, "root/BlogUrl/url");
            if (LoadNum != 0)
            {
                Console.WriteLine("Blog load " + LoadNum + " urls");
            }
            else
            {
                Console.WriteLine("Load Blog urls failed");
            }

            //Do check for each url for Blog page
            foreach (string url in BlogPageUrls)
            {
                BrowserDriver br = new BrowserDriver();
                br.Invoke(BrowserType.InternetExplorer);
                br.NavigateTo(url);
                //Load two pages' elements
                var blogPage = BrowserDriver.ActiveBrowser.Page<PageElement>();
                var LivePage = BrowserDriver.ActiveBrowser.Page<WindowsLivePage>();
                // 3 spots check
                Div spotDiv = blogPage.spotDiv;
                LinkCollection spotThreeLinks = spotDiv.Links;
                if (spotThreeLinks.Count == 3)
                {
                    Console.WriteLine(br.PageTitle + " --- Blogger slot number is 3", "Pass");
                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Blogger slot number is 3 (TestCase#1215775)", "Pass");
                }
                else
                {
                    Console.WriteLine(br.PageTitle + " --- Blogger slot number is " + spotThreeLinks.Count + ", Failed");
                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Blogger slot number is " + spotThreeLinks.Count + ", Failed (TestCase#1215775)", "Failed");
                }
                // Click the Blog button and do the check inside
                LinkCollection lc = blogPage.blogLinkC.Links;
                foreach (Link link in lc)
                { 
                    if(link.Url.EndsWith("blog.aspx"))
                    {
                        link.Click();
                        Console.WriteLine(br.PageTitle);
                        if (blogPage.SignInLink.Exists)
                        {
                            blogPage.SignInLink.Click();
                            LivePage.LoginTextField.TypeText(GetUserNameFromFile());
                            LivePage.PassWDTextField.TypeText(GetUserPwdFromFile());
                            LivePage.SignBtn.Click();
                            br.RefreshDomTree();
                            if (blogPage.SignOutLink.Exists)
                            {
                                blogPage.SignOutLink.Click();
                                Console.WriteLine(br.PageTitle + " --- Sign in function Pass");
                                result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Sign in function Pass (TestCase#1215776)", "Pass");
                            }
                            else
                            {
                                Console.WriteLine("Sign in function Failed");
                                result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Sign in function Failed (TestCase#1215776)", "Failed");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Sign in function failed");
                            result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Sign in function Failed (TestCase#1215776)", "Failed");
                        }

                        if (blogPage.headImage.Exists && blogPage.footDiv.Exists && blogPage.oneOfFiveDiv.Exists && blogPage.blogger.Exists && blogPage.blogArchief.Exists)
                        { 
                            Console.WriteLine(br.PageTitle + " --- Layout checked, Pass");
                            result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Layout checked, Pass (TestCase#1215781 & #1215782)", "Pass");
                            LinkCollection nextLink = blogPage.NextDiv.Links;
                            if (nextLink.Count > 0)
                            {
                                if (nextLink[0].Text.StartsWith("Next") || nextLink[0].Text.StartsWith(">>"))
                                {
                                    nextLink[0].Click();
                                    br.RefreshDomTree();
                                    LinkCollection nextPreLinks = blogPage.NextDiv.Links;
                                    if (nextPreLinks[0].Text.Contains("Previous") ||nextPreLinks[0].Text.Contains("<"))
                                    {
                                        Console.WriteLine("Click Next function Pass");
                                        result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Click Next function Pass (TestCase#1215783)", "Pass");
                                        nextPreLinks[0].Click();
                                    }
                                    else
                                    {
                                        Console.WriteLine("Click Next function failed");
                                        result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Click Next function Failed (TestCase#1215783)", "Failed");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("Click Next function failed");
                                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Click Next function Failed (TestCase#1215783)", "Failed");
                                }
                            }
                            else
                            {
                                Console.WriteLine("Click Next function Failed");
                                result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Click Next function Failed (TestCase#1215783)", "Failed");
                            }

                        }
                        else
                        {
                            Console.WriteLine(br.PageTitle + " --- Layout checked, Failed");
                            result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Layout checked, Failed (TestCase#1215781 & #1215782)", "Failed");
                        }

                        LinkCollection blogCollection = blogPage.blogArchief.Links;
                        if (blogCollection.Count > 0)
                        {
                            blogCollection[0].Click();
                            Console.WriteLine("Go to blog detail Page Pass");
                            result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Go to blog detail Page Pass (TestCase#1215774 & #1215778)", "Pass");
                            if (blogPage.discussDiv.Exists && blogPage.headImage.Exists && blogPage.footDiv.Exists && blogPage.blogger.Exists && blogPage.blogArchief.Exists)
                            {
                                Console.WriteLine(br.PageTitle + " --- Layout checked, Pass ()");
                                result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Layout checked, Pass (TestCase1215780)", "Pass");
                            }
                            else
                            {
                                Console.WriteLine(br.PageTitle + " --- Layout checked, failed");
                                result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Layout checked, Failed (TestCase1215780)", "Failed");
                            }

                            if (blogPage.PrintLink.Exists && blogPage.EmailLink.Exists && blogPage.FacebookLink.Exists && blogPage.DiggLink.Exists)
                            {
                                Console.WriteLine("Tools bar checked, Pass");
                                result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Tools bar checked, Pass (TestCase#1215784)", "Pass");

                                if (blogPage.PrintLink.Url.Contains("/print.aspx?"))
                                {
                                    Console.WriteLine("Print Function checked, Pass");
                                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Print Function checked, Pass (TestCase#1215784)", "Pass");
                                }
                                else
                                {
                                    Console.WriteLine("Print Function checked, Failed");
                                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Print Function checked, Failed (TestCase#1215784)", "Failed");
                                }
                                if (blogPage.EmailLink.Url.StartsWith("mailto:"))
                                {
                                    Console.WriteLine("Mail Function checked, Pass");
                                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Mail Function checked, Pass (TestCase#1215784)", "Pass");
                                }
                                else
                                {
                                    Console.WriteLine("Mail Function checked, Failed");
                                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Mail Function checked, Failed (TestCase#1215784)", "Failed");
                                }
                                if (blogPage.DiggLink.Url.StartsWith("http://digg.com/submit?url="))
                                {
                                    Console.WriteLine("Digg Function checked, Pass");
                                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Digg Function checked, Pass (TestCase#1215784)", "Pass");
                                }
                                else
                                {
                                    Console.WriteLine("Digg Function checked, Failed");
                                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Digg Function checked, Failed (TestCase#1215784)", "Failed");
                                }
                                if (blogPage.FacebookLink.Url.StartsWith("http://www.facebook.com/sharer.php?u="))
                                {
                                    Console.WriteLine("FaceBook Function checked, Pass");
                                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- FaceBook Function checked, Pass (TestCase#1215784)", "Pass");
                                }
                                else
                                {
                                    Console.WriteLine("FaceBook Function checked, Failed");
                                    result.Add(br.PageTitle + "(" + br.URL + ")" + " --- FaceBook Function checked, Failed (TestCase#1215784)", "Failed");
                                }
                                
                            }
                            else
                            {
                                Console.WriteLine("Tools bar checked, Failed");
                                result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Tools bar checked, Failed (TestCase#1215784)", "Failed");
                            }

                            
                        }
                        else
                        {
                            Console.WriteLine("Go to blog detail Page failed");
                            result.Add(br.PageTitle + "(" + br.URL + ")" + " --- Go to blog detail Page Failed (TestCase#1215774 & #1215778)", "Failed");
                        }
                        break;
                    }
                }

            }
            CloseAllIEWindows();
        }

        public void CloseAllIEWindows()
        {
            try
            {
                BrowserDriver.ActiveBrowser = null;
                var ieProcesses = Process.GetProcessesByName("iexplore");
                foreach (var p in ieProcesses)
                {
                    p.Kill();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
        public int LoadUrlFromFile(List<string> list, string path)
        {
            try
            {
                XmlDocument document = new XmlDocument();
                document.Load("UrlList.xml");
                XmlNodeList nodeTotal = document.SelectNodes(path);
                foreach (XmlNode node in nodeTotal)
                {
                    list.Add(node.InnerText);
                }
                return list.Count;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return 0;
            }
        }
        public string GetUserNameFromFile()
        {
            try
            {
                XmlDocument document = new XmlDocument();
                document.Load("UrlList.xml");
                XmlNode node = document.SelectSingleNode("root/WindowsLiveUserName");

                return node.InnerText;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return "";
            }
        }
        public string GetUserPwdFromFile()
        {
            try
            {
                XmlDocument document = new XmlDocument();
                document.Load("UrlList.xml");
                XmlNode node = document.SelectSingleNode("root/WindowsLivePwd");

                return node.InnerText;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return "";
            }
        }
        public void ResultToXml()
        {
            if (result.Count > 0)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("result.xml");
                XmlNode totalnode = doc.SelectSingleNode("Result/Total");
                totalnode.InnerText = result.Count.ToString();

                int PassCount = 0;
                int FailedCount = 0;
                foreach (var item in result)
                {
                    if (item.Value == "Pass")
                    {
                        PassCount++;
                    }
                    else
                    {
                        FailedCount++;
                    }
                    XmlElement TestCase = doc.CreateElement("TestCase");
                    XmlElement Desc = doc.CreateElement("Desc");
                    Desc.InnerText = item.Key;
                    TestCase.AppendChild(Desc);
                    XmlElement CheckResult = doc.CreateElement("CheckResult");
                    CheckResult.InnerText = item.Value;
                    TestCase.AppendChild(CheckResult);
                    doc.DocumentElement.AppendChild(TestCase);
                }
                XmlNode passnode = doc.SelectSingleNode("Result/Pass");
                passnode.InnerText = PassCount.ToString();
                XmlNode failednode = doc.SelectSingleNode("Result/Failed");
                failednode.InnerText = FailedCount.ToString();
                doc.Save("FinalResult.xml");
            }
            else
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("result.xml");
                XmlNode Failed = doc.SelectSingleNode("Result/Failed");
                Failed.InnerText = "There is no test result, please re-run the tool";
                doc.Save("FinalResult.xml");
            }
        }
    }
}
